//
//  BillViewController.m
//  dangdang
//
//  Created by air on 16/1/29.
//  Copyright © 2016年 luweijie. All rights reserved.
//

#import "BillViewController.h"
#import "BillMapViewController.h"
#import "AcountBalanceViewController.h"
#import "UIImageView+WebCache.h"

@interface BillViewController ()

@property (nonatomic, strong) UIWebView * webView;
@property (nonatomic, copy) NSString * urlString;
@property (nonatomic, copy) NSString * phoneString;

@end

@implementation BillViewController

- (instancetype)init {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"BillViewController" bundle:nil];
    self = [sb instantiateViewControllerWithIdentifier:@"BillViewController"];
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self connection];
    
    [self updateUI];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (userObject.array.count == 2 && [userObject.pay_status isEqualToString:@"0"]) {
        _payLabel.text = [NSString stringWithFormat:@"￥%@", userObject.fee];
    }else{
        _bottonView.hidden = YES;
    }
    if ([_judge isEqualToString:@"sucess"]) {
        [self addBottomView];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    userObject.orderStatus = @"";
    _judge = @"";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addBottomView{
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(self.view.center.x - 60, self.view.bounds.size.height - 120, 120, 40)];
    __block int timeout = 2; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [label removeFromSuperview];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                
                label.backgroundColor = [UIColor blackColor];
                label.text = @"成功支付";
                label.textAlignment = NSTextAlignmentCenter;
                label.textColor = [UIColor whiteColor];
                label.font = [UIFont boldSystemFontOfSize:16.0f];
                label.layer.cornerRadius = 10;
                label.layer.masksToBounds = YES;
                [self.view addSubview:label];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (void)connection{
    if (![userObject.exp_uid isEqualToString:@"0"] && !(userObject.exp_uid == nil)) {
        NSString * token = userObject.accessToken;
        NSString * userIDString = userObject.exp_uid;
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:userIDString forKey:@"uid"];
        
        [self postRequestWithMethodName:@"user/get_info" andParams:params andSender:nil];
    }
}

- (void)updateUI{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:_mapButton.titleLabel.text];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
    [_mapButton setAttributedTitle:str forState:UIControlStateNormal];
    
    _rejectButton.layer.cornerRadius = 8;
    _agreeButton.layer.cornerRadius = 8;
    _confirmButton.layer.cornerRadius = 8;
    _headImageView.layer.cornerRadius = _headImageView.bounds.size.width / 2;
    _headImageView.layer.masksToBounds = YES;
    
    if (self.view.frame.size.width == 320) {
        for (NSLayoutConstraint * leftConstraint in _timeLabelConstraintArray) {
            leftConstraint.constant -= 5;
        }
        for (NSLayoutConstraint * widthConstraint in _imageViewConstraintArry) {
            widthConstraint.constant -= 35;
        }
        for (NSLayoutConstraint * lineLeftConstraint in _lineLeftConstraintArray) {
            lineLeftConstraint.constant -= 5;
        }
        _buttonConstraint.constant -= 20;
        for (UILabel * label in _billLabelArray) {
            label.font = [UIFont systemFontOfSize:15.0];
        }
        _mapButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
        _payLabel.font = [UIFont systemFontOfSize:17.0];
        _rejectButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
        _agreeButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
        _rejectButtonWidth.constant -= 20;
        _agreeButtonWidth.constant -= 10;
    }else if (self.view.frame.size.width == 414){
        for (NSLayoutConstraint * leftConstraint in _timeLabelConstraintArray) {
            leftConstraint.constant += 10;
        }
        for (NSLayoutConstraint * widthConstraint in _imageViewConstraintArry) {
            widthConstraint.constant += 20;
        }
        for (NSLayoutConstraint * lineLeftConstraint in _lineLeftConstraintArray) {
            lineLeftConstraint.constant += 10;
        }
        _buttonConstraint.constant += 20;
        _payLabel.font = [UIFont systemFontOfSize:19.0];
        _rejectButton.titleLabel.font = [UIFont systemFontOfSize:20.0];
        _agreeButton.titleLabel.font = [UIFont systemFontOfSize:20.0];
        _rejectButtonWidth.constant += 10;
        _agreeButtonWidth.constant += 30;
    }
    
    [self judgeStatus];
    _pushButton.hidden = YES;
}

- (void)judgeStatus{
    if ([userObject.orderStatus isEqualToString:@"sucess"] || userObject.array.count == 1) {
        for (UILabel * label in _timeLabelArray) {
            if (!(label.tag == 0)) {
                label.hidden = YES;
            }
        }
        for (UIImageView * imageView in _backimageArray) {
            imageView.image = [UIImage imageNamed:@"hk_bg_up.png"];
        }
        for (UILabel * label in _billLabelArray) {
            if (!(label.tag == 0)) {
                label.textColor = [UIColor lightGrayColor];
            }
        }
        _mapButton.hidden = YES;
        _topView.hidden = YES;
        _topViewConstraint.constant -= 70;
        for (NSLayoutConstraint * topConstraint in _LineConstraintArray) {
            topConstraint.constant -= 70;
        }
        _bottonView.hidden = YES;
        _confirmView.hidden = YES;
        for (int i = 0; i < userObject.array.count; i ++) {
            UILabel * label = _timeLabelArray[i];
            label.text = [NSString stringWithFormat:@"%@", [userObject.array[i] objectForKey:@"stime"]];
        }
    }else if (userObject.array.count == 2){
        for (UILabel * label in _timeLabelArray) {
            if (!(label.tag == 0) && !(label.tag == 1)) {
                label.hidden = YES;
            }
        }
        for (UIImageView * imageView in _backimageArray) {
            if (!(imageView.tag == 0)) {
                imageView.image = [UIImage imageNamed:@"hk_bg_up.png"];
            }
        }
        for (UIImageView * imageView in _pictureArray) {
            if (imageView.tag == 0) {
                imageView.image = [UIImage imageNamed:@"hk_orders_down.png"];
            }
        }
        for (UIView * view in _lineArray) {
            if (view.tag == 0) {
                view.backgroundColor = [UIColor orangeColor];
            }
        }
        for (UILabel * label in _billLabelArray) {
            if (!(label.tag == 0) && !(label.tag == 1)) {
                label.textColor = [UIColor lightGrayColor];
            }
        }
        for (int i = 0; i < userObject.array.count; i ++) {
            UILabel * label = _timeLabelArray[userObject.array.count - 1 - i];
            label.text = [NSString stringWithFormat:@"%@", [userObject.array[i] objectForKey:@"stime"]];
        }
//        if ([userObject.pay_status isEqualToString:@"0"]) {
//            _payLabel.text = [NSString stringWithFormat:@"￥%@", userObject.fee];
//        }else if ([userObject.pay_status isEqualToString:@"1"]){
//            _bottonView.hidden = YES;
//        }
        _confirmView.hidden = YES;
    }else if (userObject.array.count == 3){
        for (UILabel * label in _timeLabelArray) {
            if (label.tag == 3 || label.tag == 4) {
                label.hidden = YES;
            }
        }
        for (UIImageView * imageView in _backimageArray) {
            if (!(imageView.tag == 0) && !(imageView.tag == 1)) {
                imageView.image = [UIImage imageNamed:@"hk_bg_up.png"];
            }
        }
        for (UIImageView * imageView in _pictureArray) {
            if (imageView.tag == 0 || imageView.tag == 1) {
                imageView.image = [UIImage imageNamed:@"hk_orders_down.png"];
            }
        }
        for (UIView * view in _lineArray) {
            if (view.tag == 0 || view.tag == 1) {
                view.backgroundColor = [UIColor orangeColor];
            }
        }
        for (UILabel * label in _billLabelArray) {
            if (!(label.tag == 0) && !(label.tag == 1) && !(label.tag == 2)) {
                label.textColor = [UIColor lightGrayColor];
            }
        }
        _bottonView.hidden = YES;
        for (int i = 0; i < userObject.array.count; i ++) {
            UILabel * label = _timeLabelArray[userObject.array.count - 1 - i];
            label.text = [NSString stringWithFormat:@"%@", [userObject.array[i] objectForKey:@"stime"]];
        }
    }else if (userObject.array.count == 4){
        
        for (UILabel * label in _timeLabelArray) {
            if (label.tag == 4) {
                label.hidden = YES;
            }
        }
        for (UIImageView * imageView in _backimageArray) {
            if (imageView.tag == 3) {
                imageView.image = [UIImage imageNamed:@"hk_bg_up.png"];
            }
        }
        for (UIImageView * imageView in _pictureArray) {
            if (imageView.tag == 0 || imageView.tag == 1 || imageView.tag == 2) {
                imageView.image = [UIImage imageNamed:@"hk_orders_down.png"];
            }
        }
        for (UIView * view in _lineArray) {
            if (view.tag == 0 || view.tag == 1 || view.tag == 2) {
                view.backgroundColor = [UIColor orangeColor];
            }
        }
        for (UILabel * label in _billLabelArray) {
            if (label.tag == 4) {
                label.textColor = [UIColor lightGrayColor];
            }
        }
        _bottonView.hidden = YES;
        _confirmView.hidden = YES;
        for (int i = 0; i < userObject.array.count; i ++) {
            UILabel * label = _timeLabelArray[userObject.array.count - 1 - i];
            label.text = [NSString stringWithFormat:@"%@", [userObject.array[i] objectForKey:@"stime"]];
        }
    }else if (userObject.array.count == 5){
        for (UIImageView * imageView in _pictureArray) {
            imageView.image = [UIImage imageNamed:@"hk_orders_down.png"];
        }
        for (UIView * view in _lineArray) {
            view.backgroundColor = [UIColor orangeColor];
        }
        _bottonView.hidden = YES;
        _confirmView.hidden = YES;
        for (int i = 0; i < userObject.array.count; i ++) {
            UILabel * label = _timeLabelArray[userObject.array.count - 1 - i];
            label.text = [NSString stringWithFormat:@"%@", [userObject.array[i] objectForKey:@"stime"]];
        }
    }
}

- (IBAction)pushButton:(UIButton *)sender {
//    _topView.hidden = NO;
//    _topViewConstraint.constant += 70;
//    for (NSLayoutConstraint * topConstraint in _LineConstraintArray) {
//        topConstraint.constant += 70;
//    }
    AcountBalanceViewController * acountboardVC = [[UIStoryboard storyboardWithName:@"AcountBalanceViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"AcountBalanceViewController"];
    
    [self.navigationController pushViewController:acountboardVC animated:YES];
}

- (IBAction)pusnMapButton:(UIButton *)sender {
    BillMapViewController * mapboardVC = [[BillMapViewController alloc] init];
    
    [self.navigationController pushViewController:mapboardVC animated:YES];
}

- (IBAction)confirmButton:(UIButton *)sender {
    NSString * token = userObject.accessToken;
    NSString * userIDString = userObject.userID;
    NSString * orderIDString = userObject.ordID;
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:token forKey:@"token"];
    [params setObject:userIDString forKey:@"uid"];
    [params setObject:orderIDString forKey:@"order_id"];
    
    [self postRequestWithMethodName:@"order/confirm_order" andParams:params andSender:nil];
}

- (IBAction)bottomButton:(UIButton *)sender {
    if (sender.tag == 0) {
        NSString * token = userObject.accessToken;
        NSString * userIDString = userObject.userID;
        NSString * orderIDString = userObject.ordID;
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:userIDString forKey:@"uid"];
        [params setObject:orderIDString forKey:@"order_id"];
        
        [self postRequestWithMethodName:@"order/refuse_order" andParams:params andSender:nil];
    }else{
        NSString * token = userObject.accessToken;
        NSString * userIDString = userObject.userID;
        NSString * orderIDString = userObject.ordID;
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:userIDString forKey:@"uid"];
        [params setObject:orderIDString forKey:@"order_id"];
        
        [self postRequestWithMethodName:@"order/accpet_order" andParams:params andSender:nil];
    }
}

- (IBAction)phoneButton:(UIButton *)sender {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:_phoneString preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"呼叫" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        if (_webView == nil) {
            _webView = [[UIWebView alloc] init];
        }
        
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", _phoneString]];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        [_webView loadRequest:request];
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    }];
    [alertVC addAction:action];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

//网络连接返回数据
- (void)requestSuccessedWithResult:(id)result NSURLSessionTask:(NSURLSessionTask *)task sender:(id)sender{
    
    NSString * urlString = [NSString stringWithFormat:@"%@", task.currentRequest.URL];
    
    if ([result isKindOfClass:[NSDictionary class]]) {
        NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
        if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"order/confirm_order"]]){
            if ([code isEqualToString:@"0"]) {
//                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"验证码已发送" preferredStyle:UIAlertControllerStyleAlert];
//                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [self.navigationController popViewControllerAnimated:YES];
//                    });
//                }];
//                [alertVC addAction:action];
//                [self presentViewController:alertVC animated:YES completion:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }else if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"user/get_info"]]){
            _urlString = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"uhead"]];
            
            NSURL* imagePath = [NSURL URLWithString:_urlString];
            [_headImageView sd_setImageWithURL:imagePath];
            
            _nameLabel.text = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"uname"]];
            _phoneString = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"uphone"]];
        }else if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"order/refuse_order"]]){
            [self.navigationController popViewControllerAnimated:YES];
        }else if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"order/accpet_order"]]){
            AcountBalanceViewController * acountboardVC = [[UIStoryboard storyboardWithName:@"AcountBalanceViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"AcountBalanceViewController"];
            
            acountboardVC.bill = @"bill";
            
            acountboardVC.billViewController = self;
            
            [self.navigationController pushViewController:acountboardVC animated:YES];
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
